(function($) {
	jQuery.fn.listFile = function(options) {
		var $this = $(this);
		var opts = jQuery.extend({}, jQuery.fn.listFile.defaults, $this
				.dataOpts(), options);
		$.ajax({
			type : 'post',
			url : '/' + appName + '/ajaxFile',
			dataType : 'json',
			data : {
				relationType : opts.relationType,
				relationId : opts.relationId
			},

			success : function(json) {
				$this.find('tbody').html(opts.template({
					data : json
				}));

				// 双击打开图片
				$this.find(".dbl_show").dblclick(function() {
					var id = $(this).dataOpts().id;
					var url = "/" + appName + "/showFileToNew?id=" + id;
					window.open(url, "newwindow");
				});

				$this.find("._show").click(function() {
					var id = $(this).dataOpts().id;
					var url = "/" + appName + "/showFileToNew?id=" + id;
					window.open(url, "newwindow");
				});

				$this.find("._delete").click(function() {
					var id = $(this).dataOpts().id;
					$.ajax({
						type : 'post',
						url : '/' + appName + '/deleteFile',
						dataType : 'json',
						data : {
							id : id,
						},
						success : function(json) {
							$this.listFile(opts);

						}
					});
				});

				opts.success(json);
				$.autoHeight();
			}
		});
	};

	jQuery.fn.listFile.defaults = {
		success : function() {
		}
	};

	jQuery.fn.uploadFile = function(options) {
		var $this = $(this);
		var opts = jQuery.extend({}, $.fn.uploadFile.defaults, options);

		$this.off("change");
		$this.on("change", function() {
			if(opts.format && $.inArray($this.val().split(".")[$this.val().split(".").length-1],opts.format.split(",")) == -1){
				opts.error("格式错误！只能上传"+opts.format+"格式的文件!");
				return false;
			}


			$this.off("change");
			$.ajaxFileUpload({
				url : '/' + appName + '/upload',
				secureuri : false,
				fileElementId : $this.attr("id"),
				dataType : 'json',
				data : {
					relationType : opts.relationType,
					relationId : opts.relationId,
					id : opts.id,
					type : opts.type
				},
				success : function(data, status) {
					opts.success(data);
				},
				error : function(data, status, e) {
					opts.error();
				}
			});
		});

		$this.click();
	};

	jQuery.fn.uploadFile.defaults = {
		id : 0,
		type : '',
		success : function() {
		},
		error : function() {
		}
	};

	jQuery.fn.showFile = function(id, index) {
		$this = $(this);

		if (id > 0) {
			$this.attr("src", "/" + appName + "/download?imgindex=" + index
					+ "&id=" + id + "&t=" + (new Date()).valueOf());
		} else {
			$this.attr("src", "");
		}

		// autoHeight();
	};

})(jQuery);